/*
 * ! TODO: 201 C
 * /out/20201212/mhs/Section 200 -  Regulatory Affairs/SOP 201 -  Contacts and Submissions for FDA/C Accessing FDA Forms over the Internet
 * https://www.fda.gov/about-fda/reports-manuals-forms/forms
 * controllers\msh-fda-data-formated-20201214.json
 * @Author: Duyb
 * @Date: 2020-12-12 13:44:35
 * @Last Modified by: Duyb
 * @Last Modified time: 2020-12-14 18:42:47
 */
const fs = require('fs');
const DATA = require('./msh-fda-data-formated-20201214.json');
const axios = require('axios');

axios.defaults.timeout = 60000 * 5;

const BASE_URL = 'https://www.fda.gov';
const outPath =
  './out/20201212/mhs/Section 200 -  Regulatory Affairs/SOP 201 -  Contacts and Submissions for FDA/C Accessing FDA Forms over the Internet/file';

function getList() {
  const list = DATA.map(({ 'form-number-rewrite': uName }) =>
    uName.substring(0, uName.indexOf(' | '))
  );
  // console.log(list);

  list.forEach((path, i) => {
    setTimeout(() => {
      write(path, outPath);
    }, 1000 * i);
  });
}

function write(pathName, outPath) {
  const url =
    pathName.indexOf('http') === 0 ? pathName : `${BASE_URL}${pathName}`;

  axios
    .get(url, {
      responseType: 'stream',
    })
    .then((res) => {
      const disposition = res.headers['content-disposition'];
      const bookName = disposition
        .substring(disposition.indexOf('"') + 1, disposition.length - 1)
        .replace(/\//g, ' ');
      console.log('bookName :', bookName);
      const writer = fs.createWriteStream(`${outPath}/${bookName}`);
      res.data.pipe(writer);
      writer.on('error', (error) => {
        writer.close();
        throw error;
      });
      writer.on('close', () => {
        console.log(`success : ${bookName}`);
      });
    })
    .catch((err) => {
      console.error('axios err :', pathName, err);
      fs.appendFileSync('./msh-fda-error.txt', pathName + '\n');
    });
}

// getList();

/**
 * ! test
 */
// const url_TEST = '/media/135203/download';
// write(url_TEST, outPath);

/**
 * ! TODO: 601-1 A
 * http://www.leg.state.fl.us/Statutes/index.cfm?App_mode=Display_Statute&URL=0700-0799/0765/0765.html
 */
const url_6011A =
  'http://www.leg.state.fl.us/Statutes/index.cfm?App_mode=Display_Statute&URL=0700-0799/0765/0765.html';
const OUT__6011A =
  './out/20201212/mhs/Section 600 -  Subject Management/SOP 601 - 1 -  Obtaining and Documenting Informed Consent - Assent/A Florida State Law for Surrogate Decision Makers for Health Care Treatment';
write(url_6011A, OUT__6011A);
